#include <math.h>

#include "map.h"
#include "defs.h"
#include "graphics.h"

static int *map;
static int mapRows = 0;
static int mapCols = 0;

void loadMap(const char *filename)
{
  int c = 0, p = 0;

  FILE *mapFile = fopen(filename, "r");
  if (!mapFile)
  {
    printf("Unable to open map file.\n");
    return;
  }

  // First row contains the number of rows and columns
  fscanf(mapFile, "%u %u\n", &mapRows, &mapCols);
  map = (int *)malloc(mapRows * mapCols * sizeof(int));

  // subsequent rows have block index, or 0 for no block
  while ((c = fgetc(mapFile)) != EOF)
    if (c != '\n')
      map[p++] = (c - 48);

  fclose(mapFile);
}

int isInsideMap(float x, float y)
{
  return (x >= 0 && x <= mapCols * TILE_SIZE && y >= 0 && y <= mapRows * TILE_SIZE);
}

int mapHasWallAt(float x, float y)
{
  int mapGridIndexX, mapGridIndexY;
  if (x < 0 || x > mapCols * TILE_SIZE || y < 0 || y > mapRows * TILE_SIZE)
    return 1;

  mapGridIndexX = (int)floor(x / TILE_SIZE);
  mapGridIndexY = (int)floor(y / TILE_SIZE);
  return map[mapGridIndexY * mapCols + mapGridIndexX] != 0;
}

int getMapAt(int i, int j)
{
  return map[i * mapCols + j];
}

void renderMap()
{
  int i, j;
  SDL_Rect mapTileRect;

  for (i = 0; i < mapRows; i++)
  {
    for (j = 0; j < mapCols; j++)
    {
      int tileX = j * TILE_SIZE;
      int tileY = i * TILE_SIZE;
      colour_t tileColour = map[i * mapCols + j] != 0 ? 0xffffffff : 0x00000000;
      drawRect(tileX * MINIMAP_SCALE_FACTOR,
               tileY * MINIMAP_SCALE_FACTOR,
               TILE_SIZE * MINIMAP_SCALE_FACTOR,
               TILE_SIZE * MINIMAP_SCALE_FACTOR,
               tileColour);
    }
  }
}
